#include "util.h"
#include "client.h"
#include <sys/epoll.h>
#include<sys/socket.h>
#include <unistd.h>
#include<stdlib.h>
#include<string.h>
#define MAX_EVENTS 10
#define BUFFER_SIZE 1000

int main()
{
	// 建立TCP连接
	int clientFd = tcpConnection("127.0.0.1", "12345");
	errif(clientFd == -1,"client connection failed");

	char buf[BUFFER_SIZE];
	train_t cmdStr;

	
	int epfd = epoll_create1(0);
	errif(epfd == -1, "epoll_create1 error");

	epollAdd(epfd,STDIN_FILENO);
    epollAdd(epfd,clientFd);
	struct epoll_event events[MAX_EVENTS];

	while (1) {
		int numEvents = epoll_wait(epfd, events, MAX_EVENTS, -1);
		errif(numEvents == -1, "epoll_wait error");

		for (int i = 0; i < numEvents; ++i) {
			int fd = events[i].data.fd;

			// 处理标准输入事件,准备发送命令
			if (fd == STDIN_FILENO) {
			    memset(buf,0,sizeof(buf));
                int ret = read(STDIN_FILENO,buf,sizeof(buf));
                errif(ret == -1,"read cmd error");
                if(ret == 0)
                {
                    printf("EXIT\n");
                    break;
                }
                memset(&cmdStr,0,sizeof(cmdStr));
                buf[strlen(buf)-1]='\0';
                parseCommand(buf,strlen(buf),&cmdStr);
                sendn(clientFd,&cmdStr,4+4+cmdStr._length);
                if(cmdStr.taskType == CMD_TYPE_PUTS)
                {
                    uploadFile(clientFd,&cmdStr);
                    continue;
                }
            }
			// 处理socket事件,接受服务器返回值或者开始下载文件
			else if (fd == clientFd) {
				recv(clientFd,buf,sizeof(buf),0);
                printf("%s\n",buf);
			}
		}
	}
	close(clientFd);
	return 0;
}
